using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DealerPlatform.Common.TokenModule;
using DealerPlatform.Service.CustomerApp;
using DealerPlatform.Service.CustomerApp.Dto;
using DealerPlatform.Web.Models;
using Microsoft.AspNetCore.Mvc;

namespace DealerPlatform.Web.Controllers
{
    public class CustomerController : BaseController
    {
        private readonly ICustomerService service;
        public IConfiguration Configuration { get; }
        public CustomerController(ICustomerService service, IConfiguration configuration)
        {
            this.Configuration = configuration;
            this.service = service;            
        }

        [HttpPost]
        public async Task<string> CheckPassword(CustomerLoginDto dto)
        {
            if(string.IsNullOrWhiteSpace(dto.CustomerNo) || string.IsNullOrWhiteSpace(dto.Password))    
            {
                HttpContext.Response.StatusCode = 400;
                return "NonLoginInfo";
            }
            bool cg = await service.CheckPassword(dto);
            if(cg)
            {
                // TODO 获取用户数据
                var cust = await service.GetCustomerAsync(dto.CustomerNo)  ;
                var token = GetToken(cust.Id, cust.CustomerNo, cust.CustomerName);
                return token;
            }
            else
            {
                HttpContext.Response.StatusCode = 400;
                return "NonUser";
            }
        }
        
        private string GetToken(int cunstomerId, string cunstomerNo, string cunstomerName)
        {
            JwtTokenModel jwt = Configuration.GetSection("Jwt").Get<JwtTokenModel>();
            jwt.Id = cunstomerId.ToString();
            jwt.CustomerNo = cunstomerNo;
            jwt.CustomerName = cunstomerName;
            return TokenHelper.CreateToken(jwt);
            // Dictionary<string, string> token = new Dictionary<string, string>();
            // token.Add("Id", cunstomerId.ToString());
            // token.Add("CustomerNo", cunstomerNo);
            // token.Add("CustomerName", cunstomerName);
            // return TokenHelper.CreateToken2(jwt, token);
        }
    }
}